package com.hadluo.qq.server.controller;

import com.hadluo.qq.server.entity.Group;
import com.hadluo.qq.server.entity.GroupMember;
import com.hadluo.qq.server.entity.GroupMessage;
import com.hadluo.qq.server.entity.User;
import com.hadluo.qq.server.mapper.GroupMessageMapper;
import com.hadluo.qq.server.service.GroupMessageService;
import com.hadluo.qq.server.service.GroupService;
import com.hadluo.qq.server.service.UserService;
import com.hadluo.qq.server.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/group")
public class GroupController {

    @Autowired
    private GroupService groupService;

    @Autowired
    private UserService userService;
    @Autowired
    GroupMessageService groupMessageService;
    @Autowired
    GroupMessageMapper groupMessageMapper;

    @PostMapping("/create")
    public Result createGroup(@RequestBody Map<String, Object> params) {
        try {
            String ownerQQNumber = (String) params.get("ownerQQNumber");
            String groupName = (String) params.get("groupName");
            String description = (String) params.get("description");
            List<String> memberQQNumbers = (List<String>) params.get("memberQQNumbers");

            // 验证必要参数
            if (ownerQQNumber == null || groupName == null || memberQQNumbers == null) {
                return Result.error("缺少必要参数");
            }

            // 获取群主用户信息
            User owner = userService.findByQQNumber(ownerQQNumber);
            if (owner == null) {
                return Result.error("群主用户不存在");
            }

            // 获取成员用户ID列表
            List<Long> memberUserIds = new ArrayList<>();
            for (String qqNumber : memberQQNumbers) {
                User member = userService.findByQQNumber(qqNumber);
                if (member != null) {
                    memberUserIds.add(member.getId());
                }
            }

            // 创建群组
            Group group = new Group();
            group.setGroupName(groupName);
            group.setDescription(description);
            Group createdGroup = groupService.createGroup(group, owner.getId(), memberUserIds);

            return Result.success(createdGroup);
        } catch (Exception e) {
            return Result.error("创建群组失败：" + e.getMessage());
        }
    }

    @GetMapping("/list")
    public Result getUserGroups(@RequestParam String qqNumber) {
        try {
            User user = userService.findByQQNumber(qqNumber);
            if (user == null) {
                return Result.error("用户不存在");
            }

            List<Group> groups = groupService.getUserGroups(user.getId());
            List<Map<String, Object>> groupsWithLastMessage = new ArrayList<>();
            for (Group group : groups) {
                // 查询 最后一次聊天记录
                GroupMessage groupMessage = groupMessageMapper.selectLastMessageByGroupId(group.getId());
                if(groupMessage != null){
                    group.setLastMessage(groupMessage.getContent());
                    group.setLastMessageTime(groupMessage.getCreatedAt().getTime());
                }
            }
            return Result.success(groups);
        } catch (Exception e) {
            return Result.error("获取群组列表失败：" + e.getMessage());
        }
    }

    @GetMapping("{groupId}/members")
    public Result getGroupMembers(@PathVariable Long groupId) {
        try {
            List<GroupMember> members = groupService.getGroupMembers(groupId);
            List<Map<String, Object>> memberDetails = new ArrayList<>();

            for (GroupMember member : members) {
                User user = userService.findById(member.getUserId()).get();
                if (user != null) {
                    Map<String, Object> detail = new HashMap<>();
                    detail.put("id", member.getId());
                    detail.put("groupId", member.getGroupId());
                    detail.put("userId", member.getUserId());
                    detail.put("qqNumber", user.getQqNumber());
                    detail.put("nickname", user.getNickname());
                    detail.put("avatar", user.getAvatar());
                    detail.put("role", member.getRole());
                    detail.put("joinTime", member.getJoinTime());
                    detail.put("alias", member.getAlias());
                    memberDetails.add(detail);
                }
            }

            return Result.success(memberDetails);
        } catch (Exception e) {
            return Result.error("获取群成员列表失败：" + e.getMessage());
        }
    }

    @GetMapping("/{groupId}/members/detail")
    public Result getGroupMembersDetail(@PathVariable Long groupId) {
        try {
            List<GroupMember> members = groupService.getGroupMembers(groupId);
            List<Map<String, Object>> memberDetails = new ArrayList<>();

            for (GroupMember member : members) {
                User user = userService.findById(member.getUserId()).get();
                if (user != null) {
                    Map<String, Object> detail = new HashMap<>();
                    detail.put("qqNumber", user.getQqNumber());
                    detail.put("nickname", user.getNickname());
                    detail.put("avatar", user.getAvatar());
                    detail.put("role", member.getRole());
                    detail.put("joinTime", member.getJoinTime());
                    detail.put("alias", member.getAlias());
                    memberDetails.add(detail);
                }
            }

            return Result.success(memberDetails);
        } catch (Exception e) {
            return Result.error("获取群成员详细信息失败：" + e.getMessage());
        }
    }

    @PostMapping("/{groupId}/members")
    public Result addGroupMembers(@PathVariable Long groupId, @RequestBody List<String> memberQQNumbers) {
        try {
            List<Long> memberUserIds = new ArrayList<>();
            for (String qqNumber : memberQQNumbers) {
                User member = userService.findByQQNumber(qqNumber);
                if (member != null) {
                    memberUserIds.add(member.getId());
                }
            }

            groupService.addGroupMembers(groupId, memberUserIds);
            return Result.success("添加群成员成功");
        } catch (Exception e) {
            return Result.error("添加群成员失败：" + e.getMessage());
        }
    }

    @DeleteMapping("/{groupId}/members/{qqNumber}")
    public Result removeGroupMember(@PathVariable Long groupId, @PathVariable String qqNumber) {
        try {
            User member = userService.findByQQNumber(qqNumber);
            if (member == null) {
                return Result.error("用户不存在");
            }

            groupService.removeGroupMember(groupId, member.getId());
            return Result.success("移除群成员成功");
        } catch (Exception e) {
            return Result.error("移除群成员失败：" + e.getMessage());
        }
    }

    @PutMapping("/{groupId}")
    public Result updateGroup(@PathVariable Long groupId, @RequestBody Group group) {
        try {
            group.setId(groupId);
            Group updatedGroup = groupService.updateGroup(group);
            return Result.success(updatedGroup);
        } catch (Exception e) {
            return Result.error("更新群组信息失败：" + e.getMessage());
        }
    }

    @DeleteMapping("/{groupId}")
    public Result dissolveGroup(@PathVariable Long groupId, @RequestParam String operatorQQNumber) {
        try {
            User operator = userService.findByQQNumber(operatorQQNumber);
            if (operator == null) {
                return Result.error("操作者不存在");
            }

            groupService.dissolveGroup(groupId, operator.getId());
            return Result.success("解散群组成功");
        } catch (Exception e) {
            return Result.error("解散群组失败：" + e.getMessage());
        }
    }

    @GetMapping("/search")
    public Result searchGroups(@RequestParam String keyword) {
        try {
            List<Group> groups = groupService.searchGroups(keyword);
            return Result.success(groups);
        } catch (Exception e) {
            return Result.error("搜索群组失败：" + e.getMessage());
        }
    }

    @GetMapping("/{groupId}")
    public Result getGroupInfo(@PathVariable Long groupId) {
        try {
            Group group = groupService.getGroupById(groupId);
            if (group == null) {
                return Result.error("群组不存在");
            }
            return Result.success(group);
        } catch (Exception e) {
            return Result.error("获取群组信息失败：" + e.getMessage());
        }
    }

    @GetMapping("/number/{groupNumber}")
    public Result getGroupByNumber(@PathVariable String groupNumber) {
        try {
            Group group = groupService.getGroupByNumber(groupNumber);
            if (group == null) {
                return Result.error("群组不存在");
            }
            return Result.success(group);
        } catch (Exception e) {
            return Result.error("获取群组信息失败：" + e.getMessage());
        }
    }

    @GetMapping("/history/{groupId}")
    public Result getGroupChatHistory(@PathVariable Long groupId, @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "20") int size) {
        try {
            List<GroupMessage> messages = groupMessageService.getGroupMessages(groupId, page, size);

            for (GroupMessage message : messages) {
                //查用户
                User user = userService.findByQQNumber(message.getSenderId()+"");
                message.setUser(user);
                message.setTimestamp(message.getCreatedAt().getTime());
            }
            return Result.success(messages);
        } catch (Exception e) {
            return Result.error("获取群聊历史记录失败：" + e.getMessage());
        }
    }
}